package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.Gjjutil.Base64Utils;
import com.block.datapush.service.apipush.utils.Gjjutil.RSAUtils;
import com.block.datapush.service.apipush.utils.GongjijinUtil;
import com.block.datapush.service.apipush.utils.HaoHuiTuiUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDate;
import java.util.*;

/**
 * 92  好汇推
 */
@Service
public class HaoHuiTuiPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String phone = memberSourceInfo.getMobileMd5().toUpperCase();
        long timestamp = System.currentTimeMillis();


        Map<String, Object> signMap = new HashMap<>();
        signMap.put("md5Phone", phone);
        signMap.put("timestamp", timestamp);


        String signMd5 = getSignStr(signMap, pushApiKeyParam.getApiSecret());

        Map<Object, Object> bizMap = new HashMap<>();
        bizMap.put("md5Phone", phone);
        bizMap.put("timestamp", timestamp);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("sign", signMd5);
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("osType", "android");
        bizMap.put("sex",memberSourceInfo.getSex()==1?"SM":"SW");
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("profession", HaoHuiTuiUtil.getJob(memberSourceInfo.getGongzuo()));
        String H = HaoHuiTuiUtil.getShangBan1(memberSourceInfo.getGongzuo());
        String D = HaoHuiTuiUtil.getShangBan(memberSourceInfo.getGongzuo());
        if(StrUtil.isNotEmpty(H)){
            bizMap.put("workingAge", H);
            bizMap.put("payType", D);
        }
        String job1 = HaoHuiTuiUtil.getJob1(memberSourceInfo.getGongzuo());
        if (StrUtil.isNotEmpty(job1)){
            bizMap.put("registerTime",job1);
            bizMap.put("taxes", HaoHuiTuiUtil.getJob2(memberSourceInfo.getGongzuo()));
            bizMap.put("invoicing",HaoHuiTuiUtil.getJob3(memberSourceInfo.getGongzuo()));
        }
        bizMap.put("loan", HaoHuiTuiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", HaoHuiTuiUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("education", HaoHuiTuiUtil.getXueLi(memberSourceInfo.getXueli()));
        bizMap.put("socialSecurity", HaoHuiTuiUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("providentFund", HaoHuiTuiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("estate", HaoHuiTuiUtil.getHouse(memberSourceInfo.getHouse()));
        String house1 = HaoHuiTuiUtil.getHouse1(memberSourceInfo.getHouse());
        if(StrUtil.isNotEmpty(house1)){
            bizMap.put("estateType",house1);
        }
        bizMap.put("car", HaoHuiTuiUtil.getCar(memberSourceInfo.getCar()));
        String car1 = HaoHuiTuiUtil.getCar1(memberSourceInfo.getCar());
        if(StrUtil.isNotEmpty(car1)){
            bizMap.put("carType", car1);
            bizMap.put("carAmount", HaoHuiTuiUtil.getCar2(memberSourceInfo.getCar()));
        }
        bizMap.put("personalInsurance", HaoHuiTuiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("creditScore", HaoHuiTuiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("wldLoan", HaoHuiTuiUtil.getWeiLi(memberSourceInfo.getWeili()));
        bizMap.put("creditCard", HaoHuiTuiUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("creditRecord", HaoHuiTuiUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("jdWhite", HaoHuiTuiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("aliBei", HaoHuiTuiUtil.getHuabei(memberSourceInfo.getHuabei()));

        String content = encrypt(JSON.toJSONString(bizMap),pushApiKeyParam.getApiKey());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",content);
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());
        paramMap.put("version","1.0");

        log.info("【好汇推半流程分润】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【好汇推半流程分润】撞库结束【result】{}", result);

        JSONObject head = resultObject.getJSONObject("head");
        JSONObject body = resultObject.getJSONObject("body");
        String returnCode = head.getString("returnCode");
        boolean results = body.getBoolean("result");
        if(!results){
            //String serialNo = head.getString("serialNo");
            pushApiResult.setCode("111111");
            pushApiResult.setMessage("撞库失败");
        }
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(returnCode), "000000") && results) {
            pushApiResult.setCode(returnCode);
            pushApiResult.setMessage(head.getString("returnMessage"));
            pushApiResult.setPushSuccess(true);
            pushApiResult.setApproveUrl(body.getString("jumpUrl"));
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            pushApiResult.setOutOrderNo(phone);
            extJson.put("outOrderNo", phone);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                BigDecimal price = body.getBigDecimal("orderPrice");//下游返回分润前价格
                if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceRight = typeRate.multiply(price);//分润后价格
                pushApiResult.setPrice(price);
                pushApiResult.setPriceRight(priceRight);
            }
            return pushApiResult;
        }
        return pushApiResult;
    }

    private String getSignStr(Map<String,Object> signMap, String secretKey) {
        // 获取并排序键列表
        List<String> keyList = new ArrayList<>(signMap.keySet());
        Collections.sort(keyList);

        // 构建签名字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : keyList) {
            if (!"sign".equalsIgnoreCase(key)) { // 排除 sign 字段本身
                Object value = signMap.get(key);
                if (value != null) {
                    stringBuilder.append(StrUtil.format("{}={}&", key, value));
                }
            }
        }
        stringBuilder.append(StrUtil.format("secretKey={}", secretKey));

        // 去除最后一个多余的 &
        if (stringBuilder.length() > 0 && stringBuilder.charAt(stringBuilder.length() - 1) == '&') {
            stringBuilder.setLength(stringBuilder.length() - 1);
        }

        // 计算 MD5 签名
        return DigestUtil.md5Hex(stringBuilder.toString()).toUpperCase();

    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);


        String requestUrl = pushApiKeyParam.getRegisterUrl();

        long timestamp = System.currentTimeMillis();

        Map<String, Object> signMap = new HashMap<>();
        signMap.put("channelUserId", memberSourceInfo.getMobile());
        signMap.put("timestamp", timestamp);
        signMap.put("name", memberSourceInfo.getRealname());
        signMap.put("phone", memberSourceInfo.getMobile());


        String signMd5 = getSignStr(signMap,pushApiKeyParam.getApiSecret());

        Map<Object, Object> bizMap = new HashMap<>();
        bizMap.put("channelUserId",  memberSourceInfo.getMobile());
        bizMap.put("timestamp", timestamp);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("sign", signMd5);
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("osType", "android");
        bizMap.put("idCardNo", memberSourceInfo.getIdcard());
        bizMap.put("sex",memberSourceInfo.getSex()==1?"SM":"SW");
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("profession", HaoHuiTuiUtil.getJob(memberSourceInfo.getGongzuo()));
        String H = HaoHuiTuiUtil.getShangBan1(memberSourceInfo.getGongzuo());
        String D = HaoHuiTuiUtil.getShangBan(memberSourceInfo.getGongzuo());
        if(StrUtil.isNotEmpty(H)){
            bizMap.put("workingAge", H);
            bizMap.put("payType", D);
        }
        String job1 = HaoHuiTuiUtil.getJob1(memberSourceInfo.getGongzuo());
        if (StrUtil.isNotEmpty(job1)){
            bizMap.put("registerTime",job1);
            bizMap.put("taxes", HaoHuiTuiUtil.getJob2(memberSourceInfo.getGongzuo()));
            bizMap.put("invoicing",HaoHuiTuiUtil.getJob3(memberSourceInfo.getGongzuo()));
        }
        bizMap.put("loan", HaoHuiTuiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", HaoHuiTuiUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("education", HaoHuiTuiUtil.getXueLi(memberSourceInfo.getXueli()));
        bizMap.put("socialSecurity", HaoHuiTuiUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("providentFund", HaoHuiTuiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("estate", HaoHuiTuiUtil.getHouse(memberSourceInfo.getHouse()));
        String house1 = HaoHuiTuiUtil.getHouse1(memberSourceInfo.getHouse());
        if(StrUtil.isNotEmpty(house1)){
            bizMap.put("estateType",house1);
        }
        bizMap.put("car", HaoHuiTuiUtil.getCar(memberSourceInfo.getCar()));
        String car1 = HaoHuiTuiUtil.getCar1(memberSourceInfo.getCar());
        if(StrUtil.isNotEmpty(car1)){
            bizMap.put("carType", car1);
            bizMap.put("carAmount", HaoHuiTuiUtil.getCar2(memberSourceInfo.getCar()));
        }
        bizMap.put("personalInsurance", HaoHuiTuiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("creditScore", HaoHuiTuiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("wldLoan", HaoHuiTuiUtil.getWeiLi(memberSourceInfo.getWeili()));
        bizMap.put("creditCard", HaoHuiTuiUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("creditRecord", HaoHuiTuiUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("jdWhite", HaoHuiTuiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("aliBei", HaoHuiTuiUtil.getHuabei(memberSourceInfo.getHuabei()));

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String extendParams = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());
        bizMap.put("extendParams", extendParams);

        String content = encrypt(JSON.toJSONString(bizMap),pushApiKeyParam.getApiKey());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",content);
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());
        paramMap.put("version","1.0");

        log.info("【好汇推半流程分润】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);
        log.info("【好汇推半流程分润】导单结束【result】{}", resultObject);
        JSONObject head = resultObject.getJSONObject("head");

        String returnCode = head.getString("returnCode");
        String returnMessage = head.getString("returnMessage");

        pushApiResult.setCode(returnCode + "|" + returnCode);
        pushApiResult.setMessage(returnMessage);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(returnCode), "000000")) {

            JSONObject body = resultObject.getJSONObject("body");
            boolean resultFlag = body.getBoolean("result");

            if (resultFlag){
                String jumpUrl = body.getString("jumpUrl");
                String serialNo = head.getString("serialNo");
                pushApiResult.setOutOrderNo(serialNo);
                pushApiResult.setApproveUrl(jumpUrl);
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
//        PushApiResult pushApiResult = new PushApiResult();
//        pushApiResult.setPushSuccess(false);
//        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
//        String requestUrl = pushApiKeyParam.getQueryUrl();
//
//        long timestamp = System.currentTimeMillis();
//
//        Map<Object, Object> signMap = new HashMap<>();
//
//        signMap.put("orderId", pushQueryParam.getOutOrderNo());
//        signMap.put("timestamp", timestamp);
//
//        List<String> keyList = JSON.parseArray(JSON.toJSONString(signMap.keySet()), String.class);
//        Collections.sort(keyList);
//        StringBuilder stringBuilder = new StringBuilder();
//        for (String key : keyList) {
//            stringBuilder.append(StrUtil.format("{}={}&", key, signMap.get(key)));
//        }
//        stringBuilder.append(StrUtil.format("secretKey={}", pushApiKeyParam.getPubKey()));
//        String sign = stringBuilder.toString();
//        String signMd5= SecureUtil.md5(sign).toUpperCase();
//
//        Map<Object, Object> bizMap = new HashMap<>();
//        bizMap.put("orderId", pushQueryParam.getOutOrderNo());
//        bizMap.put("timestamp", timestamp);
//        bizMap.put("sign", signMd5);
//
//        String content = encrypt(JSON.toJSONString(bizMap),pushApiKeyParam.getApiKey());
//
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("content",content);
//        paramMap.put("channelCode",pushApiKeyParam.getApiCode());
//        paramMap.put("version","1.0");
//
//        log.info("【好汇推】查询开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
//        String result = HttpUtil.createPost(requestUrl)
//                .header("Content-Type", "application/json")
//                .body(JSON.toJSONString(paramMap))
//                .execute().body();
//
//        JSONObject resultObject = JSON.parseObject(result);
//        log.info("【好汇推】查询结束【result】{}", resultObject);
//        JSONObject head = resultObject.getJSONObject("head");
//        String returnCode = head.getString("returnCode");
//        String returnMessage = head.getString("returnMessage");
//
//        pushApiResult.setCode(returnCode + "|" + returnMessage );
//        pushApiResult.setMessage(returnMessage);
//        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
//        pushApiResult.setResultInfo(result);
//
//        if (StrUtil.equals(String.valueOf(returnCode), "000000") ) {
//
//            JSONObject body = resultObject.getJSONObject("body");
//            String status = body.getString("status");
//            if (StrUtil.equals(String.valueOf(status), "PENDING")){
//                pushApiResult.setPushSuccess(true);
//                pushApiResult.setSettleFlag(true);
//                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
//                return pushApiResult;
//            }
//        }
//        pushApiResult.setPushSuccess(false);
//        pushApiResult.setSettleFlag(false);
//        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
//        return pushApiResult;
        return null;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);
        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String phoneMd5 = jsonObject.getString("md5Phone");

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(phoneMd5));
        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","0");
        jsonObject.put("msg","成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    /**
     * 加密
     *
     * @param input 输入
     * @param aesKey   关键
     * @return {@code String}
     */
    public static String encrypt(String input, String aesKey) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(aesKey.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes("UTF-8"));
        } catch (Exception e) {
            log.error("aes加密错误，原因是：", e);
        }
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(crypted);
    }

    public static void main(String[] args) {


        Map<Object, Object> signMap = new HashMap<>();
        signMap.put("md5Phone", 123);
        signMap.put("timestamp ", 321);


        List<String> keyList = JSON.parseArray(JSON.toJSONString(signMap.keySet()), String.class);
        Collections.sort(keyList);
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : keyList) {
            stringBuilder.append(StrUtil.format("{}={}&", key, signMap.get(key)));
        }
        stringBuilder.append(StrUtil.format("secretKey={}", "15748"));
        String sign = stringBuilder.toString();
        String signMd5= SecureUtil.md5(sign).toUpperCase();

        System.out.println(sign);
        System.out.println(signMd5);
    }


}
